/**
 * @file server.prod.js
 * @author lavas
 */

var LavasCore = require("lavas-core-vue");
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var history = require('connect-history-api-fallback');
app.use(history());

var port = process.env.PORT || 3333;

var core = new LavasCore(__dirname);

core.init(process.env.NODE_ENV || "production")
    .then(function() {
        core.runAfterBuild();
    })
    .then(function() {
        // parse application/x-www-form-urlencoded
        app.use(bodyParser.urlencoded({ extended: false }));
        // parse application/json
        app.use(bodyParser.json());
        
        const chatServer = require("../chat-server");
        chatServer.makeTokenMap();
        chatServer.checkToken(app);
        app.use("/room", require("../chat-server/routes/room"));
        app.use("/user", require("../chat-server/routes/user"));
        app.use("/file", require("../chat-server/routes/files"));
        chatServer.httpsServer(app);
        chatServer.wsServer(app);
        chatServer.connectWithWs(app);

        app.use(core.expressMiddleware());
        app.listen(port, function() {
            console.log("server started at localhost:" + port);
        });
    })
    .catch(function(err) {
        console.log(err);
    });

// catch promise error
process.on("unhandledRejection", function(err, promise) {
    console.log("in unhandledRejection");
    console.log(err);
    // cannot redirect without ctx!
});
